package Network;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;

import android.util.Log;

public class UdpServer extends Thread
{
	DatagramSocket socket = null;
	InetAddress iNet;
	public UdpPacket lastSentPacket;
	public UdpPacket mSendPacket;
	public Vector<byte[]> mReceivedPacket = new Vector<byte[]>();
	boolean go = true;
	DatagramPacket packet, lastReceivedPacket;

	public UdpServer()
	{

		try
		{
			iNet = InetAddress.getByName(InetAddress.getLocalHost().getHostAddress());
			socket = new DatagramSocket(NetworkHandler.SERVER_PORT); //Creates a socket listening on port 2008
			socket.setSoTimeout(100);	
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public Vector<byte[]> GetReceivedPackets()
	{
		synchronized(this)
		{
			Vector<byte[]> temp = new Vector<byte[]>();
			temp.addAll(mReceivedPacket);
			mReceivedPacket.clear();
			return temp;
		}
	}

	@Override
	public void run()
	{
		
		if(socket == null)
		{
			return;
		}
		
		while(go)
		{
			Receive();
			
			if(lastReceivedPacket != null && lastReceivedPacket.getPort() != -1)
			{
				//Log.d("Server", "Sending...");
				Send();
			}
		}
		
		socket.close();
		
		Log.d("Server", "Exiting...");
	}
	
	void Send()
	{
		//Log.d("Server Sending", "Data: " + mSendPacket.AnimationState + " " + mSendPacket.Pos);
		
		if(lastSentPacket != mSendPacket)
		{
			byte[] bytes = NetworkHandler.Serialize(mSendPacket);
			DatagramPacket answerPacket;
			
			try
			{
				answerPacket = new DatagramPacket(bytes, bytes.length, lastReceivedPacket.getAddress(), lastReceivedPacket.getPort());
				socket.send(answerPacket);
				
				lastSentPacket = mSendPacket;
			}
			catch (UnknownHostException e1)
			{
				e1.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	void Receive()
	{
		//Log.d("Server", "Server receiving data");
		
		byte[] data = new byte[NetworkHandler.BYTE_SIZE];
		
		packet = new DatagramPacket(data, data.length);
		
		try
		{
			socket.receive(packet);
			
			//Log.d("server received"," " + NetworkHandler.Deserialize(data).Pos);
			if(data != null && !mReceivedPacket.contains(data))
			{
				lastReceivedPacket = packet;
				
				//synchronized(this)
				//{
					mReceivedPacket.add(data);
				//}
			}
			
			//Log.d("Server Received", "Packet size: " + data.length);
		}
		catch(InterruptedIOException e)
		{
			Log.d("InterrExe", "Server Receive Timeout");
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
